package com.github.ecbp.user.service.vo;

import com.alibaba.fastjson.JSON;
import com.github.ecbp.common.constant.ConstantCode;
import com.github.ecbp.common.security.vo.DefaultSimpleGrantedAuthority;
import com.github.ecbp.common.security.vo.DefaultUserDetails;
import com.github.ecbp.common.security.vo.DefaultUserPermission;
import com.github.ecbp.user.service.entity.TAdmin;
import com.github.ecbp.user.service.entity.TPermission;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * SpringSecurity需要的用户详情
 */
@Data
public class AdminUserDetails extends DefaultUserDetails {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private TAdmin admin;
    private List<TPermission> permissionList;

    public AdminUserDetails() {
    }

    public AdminUserDetails(TAdmin admin, DefaultUserPermission userPermission, List<TPermission> permissionList) {
        super.setId(admin.getId());
        super.setIcon(admin.getIcon());
        super.setLoginPhone(admin.getLoginPhone());
        super.setLoginName(admin.getUsername());
        super.setStatus(Objects.equals(admin.getStatus(), ConstantCode.TRUE));
        super.setUserPermission(userPermission);
        logger.info("登录信息 [{}]", JSON.toJSONString(this));

        super.setGrantedAuthorities(permissionList.stream().map(permission -> new DefaultSimpleGrantedAuthority(permission.getPower())).collect(Collectors.toList()));
        super.setPassword(admin.getPassword());
        this.admin = admin;
        this.permissionList = permissionList;
    }
}
